package cn.zyy.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 登录注册工具类
 */
public final class LoginUtil {
    private static Connection conn = null;
    static {
        InputStream ins = LoginUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties ps = new Properties();
        try {
            ps.load(ins);
            String driver = ps.getProperty("jdbc.driver");
            String url = ps.getProperty("jdbc.url");
            String username = ps.getProperty("jdbc.username");
            String password = ps.getProperty("jdbc.password");
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //登录
    public static int login(String username, String password) throws SQLException {
        Statement stmt = conn.createStatement();
        String sql = "select * from login where username = '"+username+"' and password = '"+password+"'";
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.next()) {
            return 1;
        }else {
            return 0;
        }
    }
    //注册
    public static int register(String username, String password) throws SQLException {
        Statement stmt = conn.createStatement();
        String sql = "select * from login where username = '"+username+"'";
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.next()) {
            return 0;
        }else {
            sql = "insert into login(username,password) values('"+username+"','"+password+"')";
            int line = stmt.executeUpdate(sql);
            return line;
        }
    }
    //注销
    public static void logout(String username, String password) throws SQLException {
        Statement stmt = conn.createStatement();
        String sql = "delete from login where username = '"+username+"' and password = '"+password+"'";
        stmt.executeUpdate(sql);
    }
    //获取数据库连接
    public static Connection getConnection() {
        return conn;
    }
    //释放资源
    public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
